package com.ben.utils.encrypt

import android.util.Base64
import java.lang.Exception
import java.security.Key
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

/**
 * Created by bin.yang on 2016/7/15.
 */
object AesUtil {

    private const val KEY = "H9846F3UTOXBW05SIEGKD2CVQRJZLPAN"

    fun decrypt(encryptData: String?): String? {
        var decrypt: ByteArray? = null
        try {
            val key = generateKey(KEY)
            val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
            cipher.init(Cipher.DECRYPT_MODE, key)
            decrypt = cipher.doFinal(Base64.decode(encryptData, Base64.DEFAULT))
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return decrypt?.decodeToString()?.trim { it <= ' ' }
    }

    fun decrypt(key: String, encryptData: String?): String? {
        var decrypt: ByteArray? = null
        try {
            val k = generateKey(key)
            val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
            cipher.init(Cipher.DECRYPT_MODE, k)
            decrypt = cipher.doFinal(Base64.decode(encryptData, Base64.DEFAULT))
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return decrypt?.decodeToString()?.trim { it <= ' ' }
    }

    fun encode(plainText: String): String? {
        try {
            val key = generateKey(KEY)
            val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
            cipher.init(Cipher.ENCRYPT_MODE, key)
            val encryptData = cipher.doFinal(plainText.toByteArray(charset("utf-8")))
            return Base64.encodeToString(encryptData, Base64.DEFAULT)
        } catch (e: Exception) {
        }
        return null
    }

    fun encode(key: String, plainText: String): String? {
        try {
            val k = generateKey(key = key)
            val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
            cipher.init(Cipher.ENCRYPT_MODE, k)
            val encryptData = cipher.doFinal(plainText.toByteArray(charset("utf-8")))
            return Base64.encodeToString(encryptData, Base64.DEFAULT)
        } catch (e: Exception) {
        }
        return null
    }

    @Throws(Exception::class)
    private fun generateKey(key: String): Key {
        return SecretKeySpec(key.toByteArray(), "AES")
    }
}
